package cn.iocoder.yudao.module.famous.doctor.controller.app.msg;


import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.msg.MsgConversation;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.msg.MsgRecord;
import cn.iocoder.yudao.module.famous.doctor.service.msg.MsgConversationService;
import cn.iocoder.yudao.module.famous.doctor.service.msg.MsgRecordService;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.log4j.Log4j2;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.famous.doctor.enums.ErrorCodeConstants.DIALOGUE_ID_NOT_EXISTS;
import static cn.iocoder.yudao.module.famous.doctor.enums.ErrorCodeConstants.USER_ID_NOT_EXISTS;

/**
 * @author D.Luo
 * @since 2021-03-17
 */
@RestController
@RequestMapping("manager/msg")
@Tag(name = "用户 APP - 消息管理接口")
@Log4j2
public class ManagerMsgController {
    @Autowired
    MsgRecordService msgRecordService;
    @Autowired
    MsgConversationService msgConversationService;
    @Resource
    private MemberUserMapper memberUserMapper;

    @RequestMapping(value = "hook", method = RequestMethod.POST)
    @Operation(summary = "")
    public void hook(@RequestBody String message) {
        System.out.println("message:" + message);
        JSONObject result = JSONObject.parseObject(message);
        JSONObject data = JSONObject.parseObject(result.getString("payload"));

        String action = data.getString("action");

        if (action.equals("message_publish")) {
            // 发送者id-类型
            String sendUser = data.getString("from_client_id");
            // 发送主题
            String topic = data.getString("topic");
            String[] chanel = topic.split("/");
            // 消息类型
            String msgType = chanel[0];
            // 接收者id-类型
            String fromUser = chanel[1];
            log.info("data:" + data);
            // 增加一条消息记录
            MsgRecord msg = new MsgRecord();
            msg.setContent(data.getString("payload"));
            msg.setCreateTime(LocalDateTime.now());
            msg.setFromDeleteFlag(0);
            msg.setSendDeleteFlag(0);
            msg.setState(1);
            msg.setFromUserId(Integer.parseInt(fromUser.split("-")[0]));
            msg.setFromUserType(Integer.parseInt(fromUser.split("-")[1]));
            msg.setTopic(topic);
            if ("system".equals(msgType)) {
                msg.setType(2);
                msg.setSendUserId(Integer.parseInt(sendUser.split("-")[0]));
                msg.setSendUserType(0);
            }else{
                msg.setType(1);
                msg.setSendUserId(Integer.parseInt(sendUser.split("-")[0]));
                msg.setSendUserType(Integer.parseInt(sendUser.split("-")[1]));
            }
            msgRecordService.save(msg);

            String userName = "";
            String userPhoto = "";
            if (msg.getSendUserType().equals(0)){
                // 系统
                userName = "系统";
                userPhoto = "";
            }else if (msg.getFromUserType().equals(1) || msg.getFromUserType().equals(3) || msg.getFromUserType().equals(4)){
                //  患者 / 医生 =========发送人
                MemberUserDO memberUserDO = memberUserMapper.selectById(msg.getFromUserId());
                userName =memberUserDO.getNickname();
                userPhoto =memberUserDO.getAvatar();

            }

            if (msgType.equals("system")) {
                // 判断接收用户会话里面有没有系统会话
                MsgConversation mc1 = msgConversationService.getOne(new QueryWrapper<MsgConversation>()
                        .eq("type", 2).eq("from_user_id", msg.getFromUserId())
                        .eq("from_user_type", msg.getFromUserType())
                        .last("limit 1"));
                if (mc1 == null){
                    mc1 = new MsgConversation();
                    // 新建系统会话
                    mc1.setFromUserId(msg.getFromUserId());
                    mc1.setFromUserType(msg.getFromUserType());
                    mc1.setUserName(userName);
                    mc1.setUserPhoto(userPhoto);
                    mc1.setUserId(msg.getSendUserId());
                    mc1.setUserType(msg.getSendUserType());
                    mc1.setCreateTime(LocalDateTime.now());
                    mc1.setUpdateTime(LocalDateTime.now());
                    mc1.setLastContent(data.getString("payload"));
                    mc1.setType(2);
                    mc1.setUnread(1);
                    mc1.setOrderNo("");
                    mc1.setIsClose(1);
                    mc1.setDeleteFlag(0);
                    msgConversationService.save(mc1);
                }else{
                    // 更新会话
                    mc1.setLastContent(data.getString("payload"));
                    mc1.setUpdateTime(LocalDateTime.now());
                    mc1.setUnread(mc1.getUnread()+1);
                    msgConversationService.updateById(mc1);
                }

            } else {
                // 单聊，此时判断有没有当前会话，没有新生成一条，有的话把之前的数据更新(双向数据，生成两条)
                // 通过发送用户id，发送用户id类型，接收用户id，接收用户类型，订单号（如果有）去查询会话
                String orderNo = "";
                if (chanel.length == 3){
                    orderNo = chanel[2];
                }
                MsgConversation mc1 = msgConversationService.getOne(new QueryWrapper<MsgConversation>()
                    .eq("user_id", sendUser.split("-")[0]).eq("user_type", sendUser.split("-")[1])
                    .eq("from_user_id", fromUser.split("-")[0]).eq("from_user_type", fromUser.split("-")[1])
                    .eq(StringUtils.isNotEmpty(orderNo),"order_no", orderNo)
                        .last("limit 1"));
                if (mc1 == null) {
                    // 没有聊天会话，添加一条
                    mc1 = new MsgConversation();
                    mc1.setFromUserId(msg.getFromUserId());
                    mc1.setFromUserType(msg.getFromUserType());
                    mc1.setUserName(userName);
                    mc1.setUserPhoto(userPhoto);
                    mc1.setUserId(msg.getSendUserId());
                    mc1.setUserType(msg.getSendUserType());
                    mc1.setCreateTime(LocalDateTime.now());
                    mc1.setUpdateTime(LocalDateTime.now());
                    mc1.setLastContent(data.getString("payload"));
                    mc1.setType(1);
                    mc1.setUnread(1);
                    mc1.setOrderNo(orderNo);
                    mc1.setIsClose(0);
                    mc1.setDeleteFlag(0);
                    msgConversationService.save(mc1);
                } else {
                    // 更新会话
                    mc1.setLastContent(data.getString("payload"));
                    mc1.setUpdateTime(LocalDateTime.now());
                    mc1.setUnread(mc1.getUnread()+1);
                    msgConversationService.updateById(mc1);
                }

                MsgConversation mc2 = msgConversationService.getOne(new QueryWrapper<MsgConversation>()
                        .eq("user_id", fromUser.split("-")[0]).eq("user_type", fromUser.split("-")[1])
                        .eq("from_user_id", sendUser.split("-")[0]).eq("from_user_type", sendUser.split("-")[1])
                        .eq(StringUtils.isNotEmpty(orderNo),"order_no", orderNo)
                        .last("limit 1"));
                if (mc2 == null) {
                    // 没有聊天会话，添加一条
                    mc2 = new MsgConversation();
                    mc2.setFromUserId(msg.getSendUserId());
                    mc2.setFromUserType(msg.getSendUserType());
                    // 此时，会话是自己的，需要显示接收方的头像和昵称
                    if (msg.getFromUserType().equals(1) || msg.getFromUserType().equals(3) || msg.getFromUserType().equals(4)){
                        //  患者 / 医生
                        MemberUserDO memberUserDO = memberUserMapper.selectById(msg.getSendUserId());
                        userName =memberUserDO.getNickname();
                        userPhoto =memberUserDO.getAvatar();

                    }
                    mc2.setUserName(userName);
                    mc2.setUserPhoto(userPhoto);
                    mc2.setUserId(msg.getFromUserId());
                    mc2.setUserType(msg.getFromUserType());
                    mc2.setCreateTime(LocalDateTime.now());
                    mc2.setUpdateTime(LocalDateTime.now());
                    mc2.setLastContent(data.getString("payload"));
                    mc2.setType(1);
                    mc2.setUnread(1);
                    mc2.setOrderNo(orderNo);
                    mc2.setIsClose(0);
                    mc2.setDeleteFlag(0);
                    msgConversationService.save(mc2);
                } else {
                    // 更新会话
                    mc2.setLastContent(data.getString("payload"));
                    mc2.setUpdateTime(LocalDateTime.now());
//                    mc2.setUnread(mc2.getUnread() + 1);
                    msgConversationService.updateById(mc2);
                }
            }
        } else if ("message_acked".equals(action)) {
            // 消息送达，将这个人这个会话的所有消息设为已读
//            MsgConversation cs = msgConversationService.getOne(new QueryWrapper<MsgConversation>()
//                    .eq("userId", fromUserId).eq("fromUserId", sendUserId).eq("type", 1));
//            if (cs != null && cs.getUnread() != 0) {
//                cs.setUnread(0);
//                msgConversationService.updateById(cs);
//            }
        }
    }

    @GetMapping(value = "/conversationlistNoPage")
    @Operation(summary = "会话列表")
    @Parameter(name = "userId", description = "当前用户id")
    @Parameter(name = "userType", description = "当前用户类型1.平台客服 2客户 3外部师傅 4运营商")
    public CommonResult<List<MsgConversation>> conversationlistNoPage(Integer userId, Integer userType) {
        if (StringUtils.isEmpty(userId + "")) {
            throw exception(USER_ID_NOT_EXISTS);
        }
        List<MsgConversation> msgConversationList = msgConversationService.list(
                new QueryWrapper<MsgConversation>().eq("from_user_id", userId).eq("from_user_type", userType)
                        .orderByDesc("update_time"));
        return success(msgConversationList);
    }

    @GetMapping(value = "/msglist")
    @Operation(summary = "消息记录列表")
    @Parameter(name = "pageNum", description = "当前页码")
    @Parameter(name = "pageSize", description = "每页显示记录数")
    @Parameter(name = "userId", description = "当前用户id")
    @Parameter(name = "userType", description = "当前用户类型1.平台客服 2客户 3外部师傅 4运营商")
    @Parameter(name = "fromUserId", description = "发送者用户id")
    @Parameter(name = "fromUserType", description = "发送者用户类型")
    @Parameter(name = "orderNo", description = "订单编号")
    public CommonResult<IPage<MsgRecord>> msglist(Integer userId, Integer userType, Integer fromUserId, Integer fromUserType,
                                                  String orderNo, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(userId + "") || StringUtils.isEmpty(fromUserId + "")) {
            throw exception(USER_ID_NOT_EXISTS);
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        Page<MsgRecord> page = new Page<MsgRecord>(pageNum, pageSize);
        IPage<MsgRecord> page1 = msgRecordService.page(page,
                new QueryWrapper<MsgRecord>().eq("send_user_id", userId).eq("send_user_type", userType)
                        .eq("from_user_id", fromUserId).eq("from_user_type", fromUserType)
                        .eq(StringUtils.isNotEmpty(orderNo),"order_no", orderNo)
                        .or(i -> i.eq("send_user_id", fromUserId).eq("send_user_type", fromUserType)
                                .eq("from_user_id", userId).eq("from_user_type", userType)
                                .eq(StringUtils.isNotEmpty(orderNo),"order_no", orderNo))
                        .orderByDesc("id"));
        // 将数据正序显示
        Collections.reverse(page1.getRecords());

        return success(page1);
    }

    @GetMapping(value = "/cleanUnread")
    @Operation(summary = "清除未读消息数量")
    @Parameter(name = "id", description = "会话id")
    public CommonResult<Boolean> cleanUnread(Integer id) {
        if (StringUtils.isEmpty(id + "")) {
            throw exception(DIALOGUE_ID_NOT_EXISTS);
        }
        MsgConversation mc = msgConversationService.getById(id);
        if (mc != null && mc.getUnread() != 0) {
            mc.setUnread(0);
            msgConversationService.updateById(mc);
        }
        return success(true);
    }

    @GetMapping(value = "/msgCount")
    @Operation(summary = "未读消息数量")
    @Parameter(name = "userId", description = "当前用户id")
    @Parameter(name = "userType", description = "当前用户类型1.平台客服 2客户 3外部师傅 4运营商")
    public CommonResult<Object> msgCount(Integer userId, Integer userType) {
        if (StringUtils.isEmpty(userId + "")) {
            throw exception(USER_ID_NOT_EXISTS);
        }
        List<MsgConversation> lsmc = msgConversationService
                .list(new QueryWrapper<MsgConversation>().eq("from_user_type", userType).eq("from_user_id", userId).gt("unread", 0));
        int count = 0;
        for (MsgConversation mc : lsmc) {
            count = count + mc.getUnread();
        }
        JSONObject obj = new JSONObject();
        obj.put("count",count);
        return success(obj);
    }
}
